package com.see.services.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.google.gson.Gson;
import com.see.domain.model.GoogleObject;
import com.see.domain.model.StockDetail;
import com.see.network.api.HtmlReader;
import com.see.services.api.StockDetailParser;
import com.see.util.MarketMapping;

public class StockDetailGoogleFinaceParserImpl implements StockDetailParser {

	private HtmlReader htmlReader;

	public StockDetailGoogleFinaceParserImpl(HtmlReader htmlReader) {
		this.htmlReader = htmlReader;
	}

	@Override
	public Collection<StockDetail> parse(String googleUrlString) {

		String result = htmlReader.readHtml(googleUrlString, false);
		result = result.replaceAll("//", "");
		Gson gson = new Gson();
		GoogleObject[] googleObjects = gson.fromJson(result,
				GoogleObject[].class);
		List<StockDetail> detailList = new ArrayList<StockDetail>();
		for (GoogleObject googleObject : googleObjects) {
			detailList.add(convert(googleObject));
		}

		return detailList;
	}

	private StockDetail convert(GoogleObject googleObject) {
		StockDetail stockDetail = new StockDetail();
		stockDetail.setSymbol(googleObject.getT() + "."
				+ getMarketMapping(googleObject));
		stockDetail.setPrice(Double.valueOf(googleObject.getL()));
		return stockDetail;
	}

	private String getMarketMapping(GoogleObject googleObject) {
		String market = MarketMapping.getMarketMapping(googleObject.getE()).toString();
		if ("".equals(market))
			market = googleObject.getE();

		return market;
	}

}
